package com.zs.studentmanager.utils;

import com.zs.studentmanager.entity.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;


/**
 * @author: 周小白
 * @date: 2024-01-19 20:20
 **/
public class CommonUtils {

    /**
     * 用户信息脱敏
     */
    public static User toBeSafe(User user) {
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setCreateTime(user.getCreateTime());
        safeUser.setRemarks(user.getRemarks());
        safeUser.setUpdateTime(user.getUpdateTime());
        safeUser.setRealName(user.getRealName());
        safeUser.setSex(user.getSex());
        safeUser.setStatus(user.getStatus());
        safeUser.setUserName(user.getUserName());
        safeUser.setEmail(user.getEmail());
        safeUser.setUserIcon(user.getUserIcon());
        safeUser.setRoleId(user.getRoleId());

        return safeUser;
    }


    /**
     * 获取当前登录用户id
     * @return 用户id
     */
    public static long getCurrentUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                                     .getRequest();

        String token = (String) request.getServletContext().getAttribute("token");

        if (Objects.equals(token, "") || token == null) {
            return 1L;
        } else {
            return JwtUtil.parseToken(token);
        }
    }
}
